<?php

/**
 * Subclass for representing a row from the 'sf_form_gui' table.
 *
 * 
 *
 * @package plugins.sfFormGuiPlugin.lib.model
 */ 
class PluginsfFormGui extends BasesfFormGui
{
    public function __toString() {
        return $this->getName();
    }

    public function getFormObject($c) {
        
        $form = new sfForm();
        $widgets = array();
        $validators = array();
        $labels = array();
        $defaults = array();
        foreach( $this->getSfFormGuiQuestionsOrdered() as $field ) {
            $widgets[$field->getId()] = $field->getFormFieldObject();
            $validators[$field->getId()] = $field->getFormFieldValidator();
        }
        $form->setWidgetSchema( new sfWidgetFormSchema($widgets));
        $form->setValidatorSchema( new sfValidatorSchema($validators));
        
        $form->getWidgetSchema()->setNameFormat('sf_form_gui_questions[%s]');
        
        return $form;
    }
    
    public function getSfFormGuiQuestionsOrdered() {
        $c = new Criteria;
        $c->addAscendingOrderByColumn(sfFormGuiQuestionPeer::RANK);
        return parent::getSfFormGuiQuestions($c);
    }
    
    public function getResponse($session_id) {
        
          $c = new Criteria;
          $c->add(sfFormGuiResponsePeer::SESSION_ID, $session_id);
          $response = sfFormGuiResponsePeer::doSelectOne($c);
          if(!$response) {
              $response = new sfFormGuiResponse;
              $response->setSessionId($session_id);
              $response->save();
          }
          return $response;
    }
    
    public function setResponses($session_id, $form) {
        $response = $this->getResponse($session_id);
        foreach($this->getSfformGuiQuestions() as $question ) {
            $question->setResponseQuestion($response, $form);
        }
    }
}
